package com.example.meituan.activity.man;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.meituan.R;
import com.example.meituan.activity.bean.AdminBean;
import com.example.meituan.activity.bean.BusinessBean;
import com.example.meituan.dao.AdminDao;
import com.example.meituan.until.FileImgUntil;

public class UpdateStoreActivity extends AppCompatActivity {
    AdminBean currentUser;
    AdminDao adminDao;
    String path;
    private ActivityResultLauncher<String> getContentLauncher;

    private Uri url;
    //打开文件选择器
    private void openGallery(View v){
        getContentLauncher.launch("image/*");
    }

    private int updateStore(String id, String pwd, String name, String des, String type, String path){
        BusinessBean businessBean=new BusinessBean(id, pwd, name, des, type, path);
        return adminDao.updateStore(businessBean);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_update_store);
        if(adminDao==null){
            adminDao=new AdminDao();
        }
        //实现一个返回的功能
        Toolbar toolbar=findViewById(R.id.register_man_toolbar);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                                                 @Override
                                                 public void onClick(View v) {
                                                     onBackPressed();//返回功能
                                                     //finish();

                                                 }
                                             }
        );

        EditText nameText=findViewById(R.id.update_man_name);
        EditText desText=findViewById(R.id.update_man_des);
        Spinner typeText=findViewById(R.id.update_store_list_type);

        ImageView img=findViewById(R.id.update_man_photo);
        TextView reg=findViewById(R.id.update_man_reg);
        currentUser = adminDao.getUserInfo(this);
        String businessId=currentUser.getUserId();
        BusinessBean businessBean= adminDao.getBusiness(businessId);
        nameText.setText(businessBean.getsName());
        desText.setText(businessBean.getsDescribe());
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.shop_type_array));
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        typeText.setAdapter(adapter);

        String desiredValue = businessBean.getsType();
        int position = adapter.getPosition(desiredValue);
        if (position >= 0) {
            typeText.setSelection(position, true);
        } else {
            Toast.makeText(UpdateStoreActivity.this, "没有对应的类型", Toast.LENGTH_SHORT).show();
        }
        path = businessBean.getsImg();
        Bitmap defaultDrawable = BitmapFactory.decodeFile(path);//原始照片
        img.setImageBitmap(defaultDrawable);
        String id=businessBean.getsId();
        String pwd=businessBean.getsPwd();
        getContentLauncher=registerForActivityResult(new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
                    @Override
                    public void onActivityResult(Uri result) {
                        if(result!=null)
                        {
                            img.setImageURI(result);
                            url =result;
                        }else{
                            Toast.makeText(UpdateStoreActivity.this,"未选择头像",Toast.LENGTH_SHORT).show();
                        }
                    }
                }

        );
        img.setOnClickListener(new View.OnClickListener() {
                                   @Override
                                   public void onClick(View v) {
                                       //打开手机相册,实现上传图片
                                       openGallery(v);

                                   }
                               }

        );
        reg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean isValid = true;
                boolean is=true;
                Drawable drawable = img.getDrawable();
                String name = nameText.getText().toString().trim();
                String des = desText.getText().toString().trim();

                // 验证图片是否为空
                if (drawable instanceof BitmapDrawable) {
                    Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
                    if (defaultDrawable != null && bitmap.sameAs(defaultDrawable)) {
                        is = false;
                    }
                }
                // 验证其他字段
                if (name.isEmpty()) {
                    Toast.makeText(UpdateStoreActivity.this, "请输入店铺名称", Toast.LENGTH_SHORT).show();
                    isValid = false;
                }
                if (des.isEmpty()) {
                    Toast.makeText(UpdateStoreActivity.this, "请输入店铺描述", Toast.LENGTH_SHORT).show();
                    isValid = false;
                }
                Object selectedItem = typeText.getSelectedItem();
                String selectedType = selectedItem.toString();
                if (selectedType == null) {
                    Toast.makeText(UpdateStoreActivity.this, "商品类型不能为空", Toast.LENGTH_SHORT).show();
                    isValid = false;
                }

                // 如果所有验证都通过，则进行注册操作
                if (isValid) {
                    if(is) {
                        path = FileImgUntil.getImgPath();
                        FileImgUntil.saveImageBitmapToFile(url, UpdateStoreActivity.this, path);
                    }
                    int a = updateStore(id, pwd, name, des, selectedType, path);
                    if (a == 1) {
                        Toast.makeText(UpdateStoreActivity.this, "修改成功", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(UpdateStoreActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
                    }
                }

            }
        });

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
    }
}